package com.macro.mall.portal.util;

import com.macro.mall.mapper.UmsAdminMapper;
import com.macro.mall.model.UmsAdmin;
import com.macro.mall.model.UmsAdminExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserUtils {
    @Autowired
    private UmsAdminMapper umsAdminMapper;

  public Long getUserId() {
      Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
      if (authentication != null && !(authentication instanceof AnonymousAuthenticationToken)) {
          Object principal = authentication.getPrincipal();
          if (principal instanceof UserDetails) {
              Long id = null;
              UserDetails userDetails = (UserDetails) principal;
              // 假设你的UserDetails实现中包含一个getId()方法
              UmsAdminExample example = new UmsAdminExample();
              UmsAdminExample.Criteria criteria = example.createCriteria();
              criteria.andUsernameEqualTo(userDetails.getUsername());
              List<UmsAdmin> umsAdminList = umsAdminMapper.selectByExample(example);
              if (umsAdminList != null && umsAdminList.size() > 0) {
                  for (UmsAdmin umsAdmin : umsAdminList) {
                      id = umsAdmin.getId();
                  }
                  return id;
              }
          }
      }
      return null;
  }


}
